#!/usr/bin/python
import common_util
from threading import Thread, Lock
from Queue import Queue, Empty

def nsls(path, diskOnly=True, debug=False):
    '''performs nsls command on a given path and
       returns the file names. If diskOnly is True,
       only files not migrated to Tape is listed.'''

    if diskOnly:
        cmd = 'nsls -l %s | awk \'{if (match($1,"^m.*$") == 0) {print $NF}}\'' % path
    else:
        cmd = 'nsls -l %s | awk \'{print $NF}\'' % path

    if debug:
        common_util.log(cmd)

    #return (None, None)
    return common_util.exec_cmd(cmd,max_trial=1) 

def nsrm(files, nthread=10, debug=False):
    '''performs nsrm on the given path'''

    doneList = []

    # preparing the queue for querying lfn 
    wq = Queue(len(files))
    for file in files:
        wq.put(file)

    mylock = Lock()
    def worker(id):
        while not wq.empty():
            try:
                file = wq.get(block=True, timeout=1)
                ## querying LFN using lcg-la 
                cmd = 'nsrm %s' % file

                if debug:
                    common_util.log(cmd)

                (ec, out) = common_util.exec_cmd(cmd, max_trial=1)

                if not ec:
                    mylock.acquire()
                    doneList.append(file) 
                    mylock.release()

            except Empty:
                pass

    # starting the migration threads for moving files one-by-one
    threads   = []
    for i in range(nthread):
        t = Thread(target=worker, kwargs={'id': i})
        t.setDaemon(False)
        threads.append(t)

    for t in threads:
        t.start()

    for t in threads:
        t.join()

    return doneList 
